package com.foreveross.push.tmp;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.foreveross.bsl.CmanagerModuleActivity;
import com.foreveross.bsl.manager.CubeModuleManager;
import com.foreveross.bsl.model.CubeModule;
import com.foreveross.bsl.model.MessageModuleInfo;
import com.foreveross.bsl.util.BroadcastConstans;
import com.foreveross.chameleon.AppStatus;
import com.foreveross.chameleon.manager.R;
import com.foreveross.chameleon.push.cubeparser.type.ChanmeleonMessage;
import com.foreveross.chameleon.push.cubeparser.type.PatchMessageModelEvent;
import com.foreveross.chameleonsdk.config.URL;
import com.foreveross.data.table.MessageDataModel;
import com.foreveross.module.MessageInfo;
import com.foreveross.push.NotificationPushContent;
import com.foreveross.push.nodeclient.BaseParser;
import com.foreveross.push.nodeclient.Notifier;
import com.foreveross.push.nodeclient.PushConstants;
import com.foreveross.push.url.MessageConstants;
import com.foreveross.router.MappingModel;
import com.foreveross.router.RoutingParserHelper;
import com.foreveross.zillasdk.Zilla;
import com.foreveross.zillasdk.ZillaDelegate;
import com.foss.DeviceInfoUtil;
import com.foss.GeneralUtils;
import com.google.gson.Gson;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;

import java.sql.SQLException;
import java.util.*;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;


/**
 * @author apple
 * @description 当收到消息索引后【onReceive方法触发，现在所知,socket会发送这个消息索引】,
 * 程序会主动pull消息内容【pullMessage方法,zilla】，
 * ->然后取回来的消息(可能多条)
 * ->解析成消息模型-list
 * ->添加到队列 buffer中
 * ->有个timerTask 定期检查buffer，并取出buffer中的消息
 * ->取出消息后，有的消息是指令性的，如切换用户,指令性的消息就立刻执行 savable()
 * ->非指令性的消息,存储到delayQueue中, 以通知处理
 */
public class OriginalParser extends BaseParser {

    private DelayQueue<Delayed> delayQueue = new DelayQueue<Delayed>();
    public OriginalParser(final Context context) {
        super(context);

        // 处理队列消息
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true) {
                    try {
                        Delayed delayed = delayQueue.take();
                        if(delayed instanceof ChanmeleonMessage) {
                        } else {
                            sendMessage((PatchMessageModelEvent) (delayed));
                        }
                    } catch(InterruptedException e) {
                        Log.e("", "take queue error!" + e);
                    }
                }
            }
        }).start();

        // TimerTask 做什么？
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                if(buffer.isEmpty()) {
                    return;
                }

                //
                ArrayList<MessageModuleInfo> list = new ArrayList<MessageModuleInfo>();
                List<Delayed> subBuffer = null;
                synchronized(OriginalParser.this) {
                    subBuffer = new ArrayList<Delayed>(buffer);
                    buffer.clear();
                }

                //
                PatchMessageModelEvent messageModelEvent = new PatchMessageModelEvent();
                ArrayList<String> identifierlist = new ArrayList<String>();
                for(Delayed delayed : subBuffer) {
                    ChanmeleonMessage chanmeleonMessage = ChanmeleonMessage.class.cast(delayed);
                    if(chanmeleonMessage.savable()) {
                        MessageInfo messageInfo = chanmeleonMessage.getPackedMessage();
                        if(MessageConstants.MESSAGE_TYPE_SECURITY_CONTENT.equals(messageInfo.getModuleName())) {
                            String roles = messageInfo.getModuleurl();
                            if(MessageConstants.MESSAGE_SECURITY_ROLES.equals(roles)) {
                                // 退出登录
                                if(AppStatus.USERLOGIN) {
                                    context.sendBroadcast(new Intent(BroadcastConstans.SecurityRoleChange));
                                } else {
                                    continue;
                                }

                            } else if(MessageConstants.MESSAGE_SECURITY_PRIVILEGE.equals(roles)) {
                                context.sendBroadcast(new Intent(BroadcastConstans.SecurityChange));
                            }

                        }
                        String identifier = messageInfo.getIdentifier();
                        if(!identifierlist.contains(identifier)) {
                            identifierlist.add(identifier);
                        }
                        MessageDataModel messageDataModel = new MessageDataModel(context);
                        messageDataModel.addMessageInfo(messageInfo);
                        MessageModuleInfo m = new MessageModuleInfo(messageInfo);
                        list.add(m);
                        String json = new Gson().toJson(list);
                        System.out.println("getPushMessage = " + json);
                        Intent in = new Intent(BroadcastConstans.ReceiveMessages);
                        in.putExtra("message", json);
                        context.sendBroadcast(in);
                    }
                    messageModelEvent.addChanmeleonMessage(chanmeleonMessage);
                }

                if(!messageModelEvent.isEmpty()) {
                    delayQueue.add(messageModelEvent);
                }
                //通知界面进行界面刷新
                for(String string : identifierlist) {
                    Intent intent = new Intent(BroadcastConstans.ReceiveMessage);
                    intent.putExtra("identifier", string);
                    context.sendBroadcast(new Intent(intent));
                }
            }
        }, 0, 3000);
    }

    // 存放获取的消息
    private List<Delayed> buffer = Collections.synchronizedList(new ArrayList<Delayed>());


    // 收到消息索引
    @Override
    public void onReceive(Packet packet) {
        System.out.println("packet" + packet.toXML());
        if(packet instanceof Message) {
            Message message = Message.class.cast(packet);
            synchronized(OriginalParser.this) {
                pullMessage(context);
            }
        }
    }


    /**
     * 处理消息
     */
    private void sendMessage(PatchMessageModelEvent pathMessageModelEvent) {
        if(GeneralUtils.isAppRunning()) {
            sendMessageNotification(pathMessageModelEvent);
        } else {
            startApp(pathMessageModelEvent);
        }
    }

    private void startApp(PatchMessageModelEvent patchMessageModelEvent) {
        Intent intent = new Intent();
        MappingModel mappingModel;
        String className = "";
        String moduleUrl = patchMessageModelEvent.lastChanmeleonMessage().getPackedMessage().getModuleurl();
        String moduleIdentifer = patchMessageModelEvent.lastChanmeleonMessage().getPackedMessage().getIdentifier();
        String[] value = null;
        RoutingParserHelper r = new RoutingParserHelper();
        mappingModel = r.redirectToPage(moduleUrl, moduleIdentifer);
        if(mappingModel != null) {
            String[] moduleUrlList = moduleUrl.substring(1).split("/");
            value = replacelist(moduleUrlList, mappingModel.getLinkURL());
            className = mappingModel.getPageIdentifier();
        }
        if(className != null && !className.equals("")) {
            if(value != null && !value.equals("")) {
                intent.putExtra("parameters", value);
            }
        } else {
            intent.putExtra("parameters", moduleUrl);
        }

        intent.putExtra("moduleIdentifier", moduleIdentifer);
        intent.setClass(context, CmanagerModuleActivity.class);
        ChanmeleonMessage chanmeleonMessage = patchMessageModelEvent.lastChanmeleonMessage();
        Notifier.notifyInfo(context, R.drawable.appicon, PushConstants.ID_MESSAGE_NOTIFICATION,
                            chanmeleonMessage.getPackedMessage().getTitle(),
                            chanmeleonMessage.getPackedMessage().getContent(), intent);
    }

    //模块跳转
    private void sendMessageNotification(final PatchMessageModelEvent patchMessageModelEvent) {
        Intent intent = new Intent();
        String moduleUrl = patchMessageModelEvent.lastChanmeleonMessage().getPackedMessage().getModuleurl();
        String moduleId = patchMessageModelEvent.lastChanmeleonMessage().getPackedMessage().getIdentifier();
        CubeModule cubeModule = CubeModuleManager.getInstance().getModuleByIdentify(moduleId);
        //验证模块是否存在，是否有权限，不存在跳消息盒子
        intent.putExtra("moduleIdentifier", moduleId);
        intent.setClass(context, CmanagerModuleActivity.class);
        if(cubeModule == null) {
            intent.putExtra("moduleIdentifier", MessageConstants.MESSAGE_IDENTIFIER);
        } else {//本地模块
            if(cubeModule.getLocal() != null) {
                intent = localjump(moduleUrl, intent, moduleId);
            } else {//html模块
                intent.putExtra("parameters", moduleUrl);
            }
        }

        ChanmeleonMessage chanmeleonMessage = patchMessageModelEvent.lastChanmeleonMessage();
        Notifier.notifyInfo(context, R.drawable.appicon, PushConstants.ID_MESSAGE_NOTIFICATION,
                            chanmeleonMessage.getPackedMessage().getTitle(),
                            chanmeleonMessage.getPackedMessage().getContent(), intent);

    }

    private Intent localjump(String moduleUrl, Intent intent, String moduleId) {
        RoutingParserHelper r = new RoutingParserHelper();
        MappingModel mappingModel = r.redirectToPage(moduleUrl, moduleId);
        if(mappingModel == null) {
            mappingModel = r.redirectToPage("/index", moduleId);
        }
        String className = "";
        String[] parameters = null;
        if(mappingModel != null) {
            if(moduleUrl != null && !moduleUrl.equals("")) {
                String[] moduleUrlList = moduleUrl.substring(1).split("/");
                parameters = replacelist(moduleUrlList, mappingModel.getLinkURL());
            }
            className = mappingModel.getPageIdentifier();
            if(className != null && !className.equals("")) {
                if(parameters != null && !parameters.equals("")) {
                    intent.putExtra("parameters", parameters);
                }
                intent.putExtra("className", className);
            }
        }
        return intent;
    }

    private String[] replacelist(String[] moduleUrls, String[] linkUrl) {
        int count = 0;
        String[] value;
        if(moduleUrls.length > linkUrl.length) {
            count = moduleUrls.length - linkUrl.length;
            value = new String[count];
            for(int i = 0; i < value.length; i++) {
                int moduleCount = moduleUrls.length;
                value[i] = moduleUrls[moduleCount - count + i];
            }
            return value;
        } else {
            return value = null;
        }

    }


    /**
     * 接收推送拉取消息
     *
     * @param context
     */
    private void pullMessage(final Context context) {
        try {
            //接收推送时拉取消息
            String deviceId = DeviceInfoUtil.getDeviceId();
            String appId = URL.APPKEY;
            Zilla.getZilla().pushGetMessage(context, deviceId, appId, new ZillaDelegate() {

                @Override
                public void requestSuccess(String result) {
                    try {
                        //拉取消息后解析成对象模型
                        List<Delayed> messageContent = NotificationPushContent.parseRemoteModel(result, context);
                        buffer.addAll(messageContent);

                        //发送回执
                        StringBuffer sendIDs = new StringBuffer();
                        for(Delayed d : messageContent) {
                            ChanmeleonMessage msg = (ChanmeleonMessage) d;
                            String sendid = msg.getPackedMessage().getMesssageid();
                            if(sendid != null && !sendid.equals("")) {
                                sendIDs.append(sendid + ",");
                            }
                        }
                        if(sendIDs.length() != 0) {
                            receiptsMessage(context, sendIDs.substring(0, sendIDs.length() - 1));
                        }

                    } catch(SQLException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void requestStart() {
                }

                @Override
                public void requestFailed(String errorMessage) {
                }
            });
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送回执至服务器
     *
     * @param context
     * @param msgId
     */
    private void receiptsMessage(Context context, String msgId) {
        Zilla.getZilla().pushReceived(context, msgId, new ZillaDelegate() {

            @Override
            public void requestSuccess(String result) {
            }

            @Override
            public void requestStart() {
            }

            @Override
            public void requestFailed(String errorMessage) {
            }
        });
    }
}
